package com.zy.design.demo.structural;

import java.util.HashMap;

/**
 * 享元模式
 * 特点：通过共享对象，减少对象创建，节省内存。
 *
 */
interface Flyweight {
    void operation(String context);
}

class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;

    public ConcreteFlyweight(String state) { this.intrinsicState = state; }

    public void operation(String context) {
        System.out.println("内部状态: " + intrinsicState + ", 外部状态: " + context);
    }
}

class FlyweightFactory {
    private HashMap<String, Flyweight> pool = new HashMap();

    public Flyweight getFlyweight(String key) {
        if (!pool.containsKey(key)) {
            pool.put(key, new ConcreteFlyweight(key));
        }
        return pool.get(key);
    }
}

class Main5 {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fw1 = factory.getFlyweight("A");
        fw1.operation("外部1");

        Flyweight fw2 = factory.getFlyweight("A");
        fw2.operation("外部2");

        System.out.println("是否为同一对象: " + (fw1 == fw2));
    }
}
